package com.homer.android.sdk.command.uart;

import java.net.InetAddress;

import org.apache.log4j.Logger;

import Decoder.BASE64Decoder;

import com.homer.iot.esptouch.tcp.TCPSocketClient;

public class EspCommandUartPostStatusLocal implements
		IEspCommandUartPostStatusLocal {

	private final static Logger log = Logger
			.getLogger(EspCommandUartPostStatusLocal.class);
	static int port = 8800;

	private static TCPSocketClient getTcpSocketClient(String devHost) {
		TCPSocketClient tCPSocketClient = null;
		if (null != devHost) {
			tCPSocketClient = new TCPSocketClient(devHost, port);
			return tCPSocketClient;
		} else {
			return null;
		}
	}

	private boolean postUartStatus(InetAddress inetAddress, String base64Param,
			String deviceBssid) {
		TCPSocketClient tCPSocketClient = getTcpSocketClient(inetAddress
				.getHostAddress());
		if (null == tCPSocketClient) {
			tCPSocketClient = getTcpSocketClient(inetAddress.getHostAddress());
			if (null == tCPSocketClient) {
				return false;
			}
		}
		try {

			boolean isCon = tCPSocketClient.connection();
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] paramByte = decoder.decodeBuffer(base64Param);
			if (isCon) {
				tCPSocketClient.sendData(paramByte);
				return true;

			} else {
				return false;
			}

		} catch (Exception e) {
			return false;
		} finally {
			tCPSocketClient.close();
		}

	}

	@Override
	public boolean doCommandUartPostStatusLocal(InetAddress inetAddress,
			String base64Param) {
		boolean result = postUartStatus(inetAddress, base64Param, null);
		log.debug(Thread.currentThread().toString()
				+ "##doCommandUartPostStatusInternet(inetAddress=["
				+ inetAddress + "],base64Param=[" + base64Param + "]): "
				+ result);
		return result;
	}

	@Override
	public boolean doCommandUartPostStatusLocal(InetAddress inetAddress,
			String base64Param, String deviceBssid) {
		boolean result = postUartStatus(inetAddress, base64Param, deviceBssid);
		log.debug(Thread.currentThread().toString()
				+ "##doCommandPlugPostStatusLocal(inetAddress=[" + inetAddress
				+ "],base64Param=[" + base64Param + "],deviceBssid=["
				+ deviceBssid + "]");
		return result;
	}

	@Override
	public String getLocalUrl(InetAddress inetAddress) {
		// TODO Auto-generated method stub
		return null;
	}

	

}
